﻿using System;
using System.Windows.Forms;
using MediaPortal.GUI.Library;
using MediaPortal.Dialogs;
using MediaPortal.Player;
using MediaPortal.Configuration;
using BierdopjeTV;
using System.IO;
using BierdopjeTV.Configuration;
using System.Collections.Generic;

using SQLite.NET;

using System.Diagnostics;


//namespace BierdopjeTv
namespace BierdopjeTV
{

    [PluginIcons("BierdopjeTV.Bierdopje.gif", "BierdopjeTV.BierdopjeDisabled.gif")]
    public class BierdopjeTV : GUIWindow, ISetupForm
    {

        private int Selected_ItemID_Facade = 0;
		private int Selected_Season = 0;
		private int Selected_Episode = 0;

        List<Database.GUISeries> _Shows;
        List<Database.GUISeasons> _Seasons;
        List<Database.GUIEpisodes> _Episodes;
        
        //Gui Stuff
        private string billboard_image = "";
        private string titel_serie = "";
        private int gekeken_episodes = 0;
        private int aantal_episodes = 0;


        
        public string THUMBS_FOLDER =  Config.GetFile(Config.Dir.Thumbs, "BierdopjeTV");


        [SkinControlAttribute(8)]
        protected GUILabelControl m_ShowTitel = null;

        [SkinControlAttribute(9)]
        protected GUILabelControl m_Gekeken_Episodes = null;

        [SkinControlAttribute(10)]
        protected GUILabelControl m_Aantal_Episodes = null;

        [SkinControlAttribute(11)]
        protected GUILabelControl m_Vorige_Aflevering = null;

        [SkinControlAttribute(12)]
        protected GUILabelControl m_Volgende_Aflevering = null;

        [SkinControlAttribute(14)]
        protected GUILabelControl m_Duratie = null;

        [SkinControlAttribute(15)]
        protected GUILabelControl m_ShowStatus = null;


        [SkinControlAttribute(50)]
        protected GUIFacadeControl m_Facade = null;
 
        [SkinControlAttribute(1000)]        
        protected GUIImage m_BillBoard = null;

        [SkinControlAttribute(1001)]
        protected GUIImage m_SubsNL = null;

        [SkinControlAttribute(1002)]
        protected GUIImage m_SubsEN = null;
        [SkinControlAttribute(400)]
        protected GUITextScrollUpControl m_ShowSummary = null;

        [SkinControlAttribute(900)]
        protected GUIImageList m_Score = null;

        private VideoHandler m_VideoHandler;
        private int currentSelection;


        public BierdopjeTV()
        {
         
        }

        #region ISetupForm Members

        // Returns the name of the plugin which is shown in the plugin menu
        public string PluginName()
        {
            return "BierdopjeTV";
        }

        // Returns the description of the plugin is shown in the plugin menu
        public string Description()
        {
            return "Bierdopje TV Series";
        }

        // Returns the author of the plugin which is shown in the plugin menu
        public string Author()
        {
            return "Leroy Z.";
        }

        // show the setup dialog
        public void ShowPlugin()
        {
            MessageBox.Show(Config.GetFile(Config.Dir.Database, "BierdopjeTV.db3").ToString());
            Configuration.Configuration dialog = new Configuration.Configuration();
            dialog.ShowDialog();
        }

        // Indicates whether plugin can be enabled/disabled
        public bool CanEnable()
        {
            return true;
        }

        // Get Windows-ID
        public int GetWindowId()
        {
            // WindowID of windowplugin belonging to this setup
            // enter your own unique code
            return 7413;
        }

        // Indicates if plugin is enabled by default;
        public bool DefaultEnabled()
        {
            return true;
        }

        // indicates if a plugin has it's own setup screen
        public bool HasSetup()
        {
            return true;
        }

        /// <summary>
        /// If the plugin should have it's own button on the main menu of Mediaportal then it
        /// should return true to this method, otherwise if it should not be on home
        /// it should return false
        /// </summary>
        /// <param name="strButtonText">text the button should have</param>
        /// <param name="strButtonImage">image for the button, or empty for default</param>
        /// <param name="strButtonImageFocus">image for the button, or empty for default</param>
        /// <param name="strPictureImage">subpicture for the button or empty for none</param>
        /// <returns>true : plugin needs it's own button on home
        /// false : plugin does not need it's own button on home</returns>

        public bool GetHome(out string strButtonText, out string strButtonImage,out string strButtonImageFocus, out string strPictureImage)
        {
            strButtonText = PluginName();
            strButtonImage = String.Empty;
            strButtonImageFocus = String.Empty;
            strPictureImage = String.Empty;
            return true;
        }

        // With GetID it will be an window-plugin / otherwise a process-plugin
        // Enter the id number here again
        public override int GetID
        {
            get
            {
                return 7413;
            }

            set
            {
            }
        }

        #endregion

        public override bool Init()
        {
            Helpers.Logger.Write("Bierdopje TV Gestart");
            Debug.Print("Init()");
            m_VideoHandler = new VideoHandler();
            currentSelection = 0;

            if (!Directory.Exists(THUMBS_FOLDER))
            {
                Directory.CreateDirectory(THUMBS_FOLDER);
            }

            return Load(GUIGraphicsContext.Skin + @"\BierdopjeTV.xml");
            
        }

        protected override void OnClicked(int controlId, GUIControl control, MediaPortal.GUI.Library.Action.ActionType actionType)
        {
            Debug.Print("OnClicked() : " + control.ToString() + " -> "  + actionType.ToString());
            //if (actionType != MediaPortal.GUI.Library.Action.ActionType.ACTION_SELECT_ITEM) return;
            if (control == m_Facade) //enter / click
            {
				if (currentSelection == 0) //if shows was entered
				{
                    Selected_ItemID_Facade = m_Facade.SelectedListItemIndex;
                    
				}
                if (currentSelection == 1) //if season was entered
                {
                    Selected_Season = m_Facade[m_Facade.SelectedListItemIndex].ItemId;
                    Debug.Print("selectedSeason is now : " + Selected_Season.ToString());
                }

                if (currentSelection == 2) //if episode was entered
                {
                    Selected_Episode = m_Facade[m_Facade.SelectedListItemIndex].ItemId;
                    Debug.Print("Selected_Episode is now : " + Selected_Episode.ToString());
                } 
                
                currentSelection++;


                
                if (currentSelection > 2)
                {
                    currentSelection = 3;
                }
			      
                decideListView();

            }
                    
            base.OnClicked(controlId, control, actionType);
        }

        public override void OnAction(MediaPortal.GUI.Library.Action action)
        {
            //Debug.Print("OnAction() : " + action.wID.ToString());           
            
            //Escappe is nu ingedrukt.
            if (action.wID == MediaPortal.GUI.Library.Action.ActionType.ACTION_PREVIOUS_MENU)
            {
                 
                currentSelection--;
            
                if (currentSelection == -1)
                {
                    //let do mediaportal it's action
                    base.OnAction(action);
                }
                else
                {                   
                    decideListView();
                    return;
                }
            }
            if (action.wID == MediaPortal.GUI.Library.Action.ActionType.ACTION_CONTEXT_MENU)
            {
                OnContextMenu();
            }
            base.OnAction(action);
        }

        public override bool OnMessage(GUIMessage message)
        {
            //Debug.Print("OnMessage() : " + message.Message.ToString());
            switch (message.Message)
            {
                //Als selectie gewijzigd is.
                case GUIMessage.MessageType.GUI_MSG_ITEM_FOCUS_CHANGED:
                    
                    if (message.SenderControlId == (int)m_Facade.GetID)
                    {
                        //Selection on facade has changed, do some stuff												
                        if (currentSelection == 0) //Alleen bij Series doen!
                        {
                            Series_OnItemSelected(m_Facade.SelectedListItemIndex);
                        }
                        if (currentSelection == 1) //alleen bij Seasons doen!
                        {
                            Season_OnItemSelected(m_Facade.SelectedListItemIndex);
                        }
                    }
                
                  break;
            }
            return base.OnMessage(message);
        }

        private void decideListView()
        {
            

            switch (currentSelection)
            {
                

                case 0:
                    {
                        //OnTestButton();
						Debug.WriteLine("We moeten nu de Seriesladen");
						Debug.Print("We hebben geselecteerd showid : " + m_Facade.SelectedItem.ToString());
                        
                        
                        LoadSeries();
                        break;
                    }
                case 1:
                    {
												
                        Debug.WriteLine("We moeten nu de seizoenen laden");
                        LoadSeasons(_Shows[Selected_ItemID_Facade].ShowID);
                        break;
                    }
                case 2:
                    {
                        Debug.WriteLine("We moeten nu de episodes laden");
                        LoadEpisodes(_Shows[Selected_ItemID_Facade].ShowID, Selected_Season);                    
                        break;
                    }
                case 3:
			    {
                    
				    Debug.Print("Staring videoplay");
                    m_VideoHandler.Play(@"Z:\Series\American Dad!\American.Dad.S05E05.Man.in.the.Moonbounce.PDTV.XviD-FQM\ad.505.xvid-fqm.avi");
                    m_VideoHandler.isPlaying = true;

                    Debug.Print("----------------------------------------------------");
                
				break;
				}
            }
        }

        private void OnTestButton()
        {
            //GUIDialogOK dlg = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK);
            //dlg.SetHeading("Button has been pressed");
            //dlg.SetLine(1, "You pressed button 1");
            //dlg.SetLine(2, String.Empty);
            //dlg.SetLine(3, String.Empty);
            //dlg.DoModal(GUIWindowManager.ActiveWindow);

        }

        private void OnContextMenu()
        {
            Debug.Print("OnContextMenu()");
            GUIDialogMenu dlg = (GUIDialogMenu) GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
            //GUIDialogOK dlg = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK);
            dlg.Reset();
            dlg.SetHeading(m_Facade[m_Facade.SelectedListItemIndex].Label.ToString());
            
            dlg.Add("Dit is de eerste optie");
            dlg.Add("Dit is de 2e optie");
            dlg.Add("Dit is de 3e optie");
            dlg.Add("Dit is de 4e optie");
            
            dlg.DoModal(GUIWindowManager.ActiveWindow);
            MessageBox.Show("SelectedID : " + 		dlg.SelectedLabelText);

        }

        

        protected override void OnPageLoad()
        {
            Debug.Print("OnPageLoad()");
            if (m_VideoHandler.isPlaying) {
                currentSelection = 2;
                Series_OnItemSelected(Selected_ItemID_Facade);
            }
            if (currentSelection == -1)
            {
                currentSelection = 0;
            }
            

            decideListView();
            

            this.LoadFacade();            

        }


        void LoadFacade()
        {

            m_Facade.View = GUIFacadeControl.ViewMode.List;
                        
            decideListView();

        }

        void LoadSeries()
        {

            _Shows = Database.DBShows.getShows();

			this.m_Facade.Clear();

			GUIListItem item;

			for (int i = 0; i < _Shows.Count; i++)
			{
				item = new GUIListItem();
				item.ItemId = _Shows[i].ShowID;
				item.Label = _Shows[i].ShowName;
				item.Label2 = _Shows[i].Wachted.ToString() + "/" + _Shows[i].Downloaded.ToString();
                
                //Condities om te bepalen welke kleur iets krijgt :-)
                if (_Shows[i].Wachted > _Shows[i].Downloaded)
                {
                    item.IsPlayed = true; //alle episodes zijn gezien
                    Debug.Print(_Shows[i].ShowName + " is al gezien");
                }
                if (_Shows[i].Wachted == 0) //0 items gezien
                {
                    if (_Shows[i].Downloaded == 0) //geen episodes lokaal, en niets gezien.
                    {
                        item.IsRemote = true;
                        Debug.Print(_Shows[i].ShowName + " geen episodes lokaal, en niets gezien.");
                    }
                }
				m_Facade.Add(item);
				item = null;
			}
            //selecteer wat de user geselect had :-)
            m_Facade.SelectedListItemIndex = Selected_ItemID_Facade;
			GUIControl.FocusControl(m_Facade.GetID, m_Facade.ThumbnailView.GetID);
    
        }

        void LoadSeasons(int ShowID)
        {
            Debug.Print("Ik zit nu in de LoadSeasons(Method)");
            
            //this.m_Facade.Clear();

            //GUIListItem item;
            //SQLiteResultSet _Results = Helpers.SqliteHelper.ExecuteQuery("SELECT DISTINCT Season, ShowID FROM BierdopjeEpisodes WHERE ShowID = " + ShowID.ToString());

            //int rijen = _Results.Rows.Count;

            ////If there are episodes with no online data:
            //if (rijen > 0)
            //{
            //    for (int i = 0; i < rijen; i++)
            //    {
            //        item = new GUIListItem();
            //        item.ItemId = Convert.ToInt32(_Results.Rows[i].fields[0]);
            //        item.Label = "Season " + _Results.Rows[i].fields[0].ToString();
            //        item.Label2 = _Results.Rows[i].fields[1].ToString();
            //        m_Facade.Add(item);
            //        item = null;
            //    }

            //    //GUIControl.FocusControl(m_Facade.GetID, m_Facade.ThumbnailView.GetID);
            //}

            _Seasons = Database.DBSeasons.getSeasons(ShowID);

            this.m_Facade.Clear();

            GUIListItem item;

            for (int i = 0; i < _Shows.Count; i++)
            {
                item = new GUIListItem();
                item.ItemId = _Seasons[i].Season;
                item.Label = "Season " + _Seasons[i].Season.ToString() + " (" + _Seasons[i].Episodes.ToString() + " Episodes)";
                item.Label2 = _Seasons[i].Watched.ToString() + "/" + _Seasons[i].Downloaded.ToString();

                //Condities om te bepalen welke kleur iets krijgt :-)
                if (_Seasons[i].Watched >= _Seasons[i].Downloaded)
                {
                    item.IsPlayed = true; //alle episodes zijn gezien
                    Debug.Print(_Seasons[i].Season + " is al gezien");
                }
                if (_Seasons[i].Watched == 0) //0 items gezien
                {
                    if (_Seasons[i].Downloaded == 0) //geen episodes lokaal, en niets gezien.
                    {
                        item.IsRemote = true;
                        Debug.Print(_Seasons[i].Season + " geen episodes lokaal, en niets gezien.");
                    }
                }
                m_Facade.Add(item);
                item = null;
            }
            //selecteer wat de user geselect had :-)
            //m_Facade.SelectedListItemIndex = Selected_ItemID_Facade;
            GUIControl.FocusControl(m_Facade.GetID, m_Facade.ThumbnailView.GetID);


        }

        void LoadEpisodes(int ShowID, int Season)
        {
            Debug.Print("Ik zit nu in de LoadSeasons(Method)");

            _Episodes = Database.DBEpisodes.getEpisodes(ShowID, Season);

            this.m_Facade.Clear();

            GUIListItem item;

            for (int i = 0; i < _Shows.Count; i++)
            {
                item = new GUIListItem();
                item.ItemId = _Episodes[i].EpisodeID;
                item.Label = _Episodes[i].Season.ToString() + "x" + _Episodes[i].Episode.ToString() + " " + _Episodes[i].Titel;
                item.Label2 = _Episodes[i].AirDate;

                //Condities om te bepalen welke kleur iets krijgt :-)
                if (_Episodes[i].Wachted == 1)
                {
                    item.IsPlayed = true; //alle episodes zijn gezien
                    Debug.Print(_Episodes[i].Season + " is al gezien");
                }
                m_Facade.Add(item);
                item = null;
            }
            //selecteer wat de user geselect had :-)
            //m_Facade.SelectedListItemIndex = Selected_ItemID_Facade;
            GUIControl.FocusControl(m_Facade.GetID, m_Facade.ThumbnailView.GetID);            //this.m_Facade.Clear();

        }
       
        //Serie, Season, Episode selected


        //Try to load the billboard
        void Series_OnItemSelected(int selectedIndex)
        {
            API.APIFunctions _API = new API.APIFunctions();
            //Debug.Print("Series_OnItemSelected!");

            //get the placeholder
            if (!File.Exists(THUMBS_FOLDER + @"\0.jpg"))
            {
                _API.DownloadBillBoard(0);
            }

            if (File.Exists(THUMBS_FOLDER + @"\" + _Shows[selectedIndex].ShowID + @".jpg"))
            {
                billboard_image = THUMBS_FOLDER + @"\" + _Shows[selectedIndex].ShowID + @".jpg";
            }
            else
            {
                _API.DownloadBillBoard(_Shows[selectedIndex].ShowID);
                billboard_image = THUMBS_FOLDER + @"\0.jpg";                
            }
            titel_serie = _Shows[selectedIndex].ShowName;
            gekeken_episodes = _Shows[selectedIndex].Wachted;
            aantal_episodes = _Shows[selectedIndex].Downloaded;
            //_Shows[selectedIndex].
            m_ShowSummary.Label = _Shows[selectedIndex].Summary;
            m_Score.Percentage = (Convert.ToInt32(Math.Round(Convert.ToDouble(_Shows[selectedIndex].Score))) +1) * 10;

            m_Volgende_Aflevering.Label = "Volgende aflevering: " + getDate(_Shows[selectedIndex].NextEpisode);

            m_Vorige_Aflevering.Label = "Vorige aflevering: " + getDate(_Shows[selectedIndex].LastAired);   

            m_Duratie.Label = "Duratie: " + _Shows[selectedIndex].Runtime.ToString() + " minuten.";
            m_ShowStatus.Label = "Status: " + _Shows[selectedIndex].ShowStatus;
            if (_Shows[selectedIndex].SubsNL == 0)
            {
                m_SubsNL.SetFileName(@"H:\c#\MediaPortal\BierdopjeTV-API\Resources\nl_0.gif");
            }
            else
            {
                m_SubsNL.SetFileName(@"H:\c#\MediaPortal\BierdopjeTV-API\Resources\nl_1.gif");
            }
            if (_Shows[selectedIndex].SubsEN == 0)
            {
                m_SubsEN.SetFileName(@"H:\c#\MediaPortal\BierdopjeTV-API\Resources\usa_0.gif");
            }
            else
            {
                m_SubsEN.SetFileName(@"H:\c#\MediaPortal\BierdopjeTV-API\Resources\usa_1.gif");
            }
//            fillGUIData();
            m_BillBoard.SetFileName(billboard_image);
            m_ShowTitel.Label = titel_serie;
            m_Gekeken_Episodes.Label = "Gekeken episodes: " + gekeken_episodes.ToString();
            m_Aantal_Episodes.Label = "Aantal episodes: " + aantal_episodes.ToString();

        }

        void Season_OnItemSelected(int selectedIndex)
        {
            Debug.Print(" Season_OnItemSelected(" + selectedIndex.ToString() + ")");
            Debug.Print("\t_Seasons[selectedIndex].Watched : " + _Seasons[selectedIndex].Watched.ToString());
            Debug.Print("\t_Seasons[selectedIndex].Downloaded : " + _Seasons[selectedIndex].Downloaded.ToString());
            Debug.Print("\t_Seasons[selectedIndex].SubsNL : " + _Seasons[selectedIndex].SubsNL.ToString());
            Debug.Print("\t_Seasons[selectedIndex].SubsEN : " + _Seasons[selectedIndex].SubsEN.ToString());
            
            m_Gekeken_Episodes.Label = "Gekeken episodes: " + _Seasons[selectedIndex].Watched.ToString();
            m_Aantal_Episodes.Label = "Aantal episodes: " + _Seasons[selectedIndex].Downloaded.ToString();            

            if (_Seasons[selectedIndex].SubsNL == 0)
            {
                m_SubsNL.SetFileName(@"H:\c#\MediaPortal\BierdopjeTV-API\Resources\nl_0.gif");
            }
            else
            {
                m_SubsNL.SetFileName(@"H:\c#\MediaPortal\BierdopjeTV-API\Resources\nl_1.gif");
            }
            if (_Seasons[selectedIndex].SubsEN == 0)
            {
                m_SubsEN.SetFileName(@"H:\c#\MediaPortal\BierdopjeTV-API\Resources\usa_0.gif");
            }
            else
            {
                m_SubsEN.SetFileName(@"H:\c#\MediaPortal\BierdopjeTV-API\Resources\usa_1.gif");
            }
            //Debug.Print("Another Season selected!");
        }

        private void Episode_OnItemSelected(GUIListItem item)
        {
            //Debug.Print("Another Episode selected!");
        }

        private void fillGUIData()
        {
    
            
        }

        private string getDate(string source)
        {
            string _datum;

            source.Replace("januari", "01");
            source.Replace("februari", "02");
            source.Replace("maart", "03");
            source.Replace("april", "04");
            source.Replace("mei", "05");
            source.Replace("juni", "06");
            source.Replace("juli", "07");
            source.Replace("augustus", "08");
            source.Replace("september", "09");
            source.Replace("oktober", "10");
            source.Replace("november", "11");
            source.Replace("decembeter", "12");

            //Debug.Print("Source: " + source);
            
            DateTime datum;

            datum = DateTime.Parse(source);
            string maand = "";

            switch (datum.Month)
            {
                case 1:
                    maand = "jan";
                    break;
                case 2:
                    maand = "feb";
                    break;
                case 3:
                    maand = "mrt";
                    break;
                case 4:
                    maand = "apr";
                    break;
                case 5:
                    maand = "mei";
                    break;
                case 6:
                    maand = "jun";
                    break;
                case 7:
                    maand = "jul";
                    break;
                case 8:
                    maand = "aug";
                    break;
                case 9:
                    maand = "sep";
                    break;
                case 10:
                    maand = "okt";
                    break;
                case 11:
                    maand = "nov";
                    break;
                case 12:
                    maand = "dec";
                    break;
            }

            _datum = datum.Day.ToString() + "-" + maand + "-" + datum.Year.ToString();
            if (datum.Year == 1970)
            {
                _datum = "(onbekend)";
            }
            //Debug.Print("Datum:" + _datum);
            return _datum;

        }
    }
}